package com.controller.backend.teac;

import com.entity.Teacher;
import com.entity.User;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet("/backend/teachers")
public class BackTeachersServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Teacher> teachers = new ArrayList<>();
        String sql = "select * from teachers";
        try (Connection conn = DataSourceUtils.getConnection();
             PreparedStatement st = conn.prepareStatement(sql)) {
            try(ResultSet rs = st.executeQuery(sql)) {
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String name = rs.getString("name");
                    String grade = rs.getString("grade");
                    String img = rs.getString("img");
                    String intro = rs.getString("intro");
                    String inName = null;
                    if (grade.equals("professor")) {
                        inName = "教授";
                    } else if (grade.equals("associate")) {
                        inName = "副教授";
                    } else if (grade.equals("lecturer")) {
                        inName = "讲师";
                    }
                    Teacher teacher = new Teacher(id, name, inName, img, intro);
                    teachers.add(teacher);
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        User user = (User) req.getSession().getAttribute("user");
        if (user != null) {
            req.setAttribute("username", user.getUserName());
            req.setAttribute("teachers", teachers);
            req.getRequestDispatcher("/WEB-INF/backend/teacher.jsp").forward(req, resp);
        } else {
            resp.sendRedirect(req.getContextPath() + "/login");
        }
    }
}
